from common.stream.push import MediaPush
from common.files.media import MediaFile
from common.utils.toolkit import ToolKit
from common.utils.toolkit import Log
import threading
class FilmSchedule:
    __instance = None
    OPEN_TIME = 6 * 60
    CLOSE_TIME = 23 * 60
    SCHEDULE_EVERYDAY_FIVE_AM = 5
    def __new__(cls, *args, **kwargs):
        if not cls.__instance:
            cls.__instance = super().__new__(cls, *args, **kwargs)
        return cls.__instance

    def __init__(self):
        try:
            len(self.timetable.keys())
        except:
            self.timetable = {}
            self.films = {}
            self.playlist = []
            self.running = False
            self.mediadir = None 

    def setMediaDir(self, mediadir):
        self.mediadir = mediadir

    def start(self):
        self.running = True
        hastask = False
        now = ToolKit.getTimeNow()
        nowtime = now.hour * 60 + now.minute
        for item in self.playlist:
            if(item['time'] > nowtime):
                interval = (item['time'] - nowtime) * 60
                Log.i("will play at {}, after {} seconds".format(self.tranlateTime(item['time']), interval))
                timer = threading.Timer(interval, self.cmd, args=[item['path']])
                hastask = True
                timer.start()
                break
        if(not hastask):
            Log.i("Add Next Schedule")
            self.running = False
            self.__startNextSchedule()
        Log.i("Schedule is running? {}".format(self.running))
             

    def cmd(self, path):
        MediaPush.push(path)
        self.start()

    def createPlayListTask(self, mediadir):
        Log.i("Create Play List")
        self.films.clear()
        map = MediaFile().queryMediaFiles(mediadir)
        for fileinfo in map.values():
            self.__requestShown(fileinfo['id'], fileinfo['path'], fileinfo['duration'])
        self.__releaseTimetable()
        self.start()

    def addNextSchedule(self):
        date = ToolKit.getNextTime(FilmSchedule.SCHEDULE_EVERYDAY_FIVE_AM)
        if(ToolKit.isTomorrow(date)):
            self.createPlayListTask(self.mediadir)
        else:
            self.__startNextSchedule()

    def __startNextSchedule(self):
        date = ToolKit.getNextTime(FilmSchedule.SCHEDULE_EVERYDAY_FIVE_AM)
        interval = ToolKit.calcIntervalSeconds(date)
        Log.i("Will Update Timetable After {} Seconds".format(interval))
        timer = threading.Timer(interval, self.createPlayListTask, args=[self.mediadir])
        timer.start()

    def __requestShown(self, id, path, duration):
        Log.i("{} request shown:{} | {}".format(path, duration, self.running))
        if(not self.running):
            self.films[id] = {'path':path, 'duration':int(duration/60) + 2}
            self.timetable[id] = []
        Log.d("films:{}".format(self.films.values()))
        
    def tranlateTime(self, mins):
        hours = int(mins/60)
        mins -= (hours * 60)
        return "{:0>2d}:{:0>2d}:00".format(hours, int(mins))

    def __releaseTimetable(self):
        Log.i("Calc Timetable")
        self.playlist.clear()
        start = FilmSchedule.OPEN_TIME
        while(start <= FilmSchedule.CLOSE_TIME and len(self.films.keys()) > 0 ):
            for film in self.films.keys():
                time = self.tranlateTime(start)
                self.timetable[film].append(time)
                self.playlist.append({'path':self.films[film]['path'], 'time':start})
                Log.d("{}:{}".format(film, start))
                start += self.films[film]['duration']
                if(start > FilmSchedule.CLOSE_TIME):
                    break
        Log.i("Calc Timetable end.")

    def getTimetable(self, film):
        tb = ['未排片']
        if(film in self.timetable.keys()):
            tb = self.timetable[film]
        return tb
